"""
认证相关的API
包括登录、注册、令牌刷新等功能
"""
from flask import request, jsonify
from flask_jwt_extended import (
    create_access_token, jwt_required, current_user, get_jwt_identity
)
from app.extensions import db
from app.models.user import User, UserRole
from app.schemas.user import LoginSchema, UserSchema, PasswordChangeSchema
from app.utils.errors import UnauthorizedError, BadRequestError
from app.api.v1 import api_v1

@api_v1.route('/auth/login', methods=['POST'])
def login():
    """用户登录接口"""
    data = request.get_json()
    
    # 检查必填参数
    if not data or not data.get('username') or not data.get('password'):
        return jsonify({"msg": "缺少用户名或密码"}), 400
    
    schema = LoginSchema()
    errors = schema.validate(data)
    if errors:
        return jsonify({"msg": "请求参数错误", "errors": errors}), 400
    
    # 验证用户
    user = User.query.filter_by(username=data['username']).first()
    if user and user.check_password(data['password']):
        if not user.is_active:
            return jsonify({"msg": "用户已禁用"}), 401
        
        # 创建访问令牌
        access_token = create_access_token(identity=user)
        
        return jsonify({
            "msg": "登录成功",
            "access_token": access_token,
            "user": {
                "id": user.id,
                "username": user.username,
                "email": user.email,
                "role": user.role,
                "full_name": user.full_name
            }
        }), 200
    
    return jsonify({"msg": "用户名或密码错误"}), 401

@api_v1.route('/auth/refresh', methods=['POST'])
@jwt_required()
def refresh():
    """刷新访问令牌"""
    # 从JWT获取用户身份
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    
    if not user or not user.is_active:
        return jsonify({"msg": "用户不存在或已禁用"}), 401
    
    # 创建新令牌
    access_token = create_access_token(identity=user)
    
    return jsonify({
        "msg": "令牌刷新成功",
        "access_token": access_token
    }), 200

@api_v1.route('/auth/profile', methods=['GET'])
@jwt_required()
def get_profile():
    """获取当前用户资料"""
    return jsonify(current_user.to_dict()), 200

@api_v1.route('/auth/register', methods=['POST'])
def register():
    """用户注册接口"""
    data = request.get_json()
    
    schema = UserSchema()
    try:
        # 使用schema验证数据
        schema.load(data)
    except Exception as e:
        return jsonify({"msg": str(e), "errors": e.messages if hasattr(e, 'messages') else None}), 400
    
    # 创建新用户
    user = User(
        username=data['username'],
        email=data['email'],
        full_name=data.get('full_name'),
        role=UserRole.USER.value,  # 默认为普通用户
        is_active=True
    )
    user.set_password(data['password'])
    
    db.session.add(user)
    db.session.commit()
    
    # 创建访问令牌
    access_token = create_access_token(identity=user)
    
    return jsonify({
        "msg": "注册成功",
        "access_token": access_token,
        "user": {
            "id": user.id,
            "username": user.username,
            "email": user.email,
            "role": user.role,
            "full_name": user.full_name
        }
    }), 201

@api_v1.route('/auth/change-password', methods=['PUT'])
@jwt_required()
def change_password():
    """修改密码"""
    data = request.get_json()
    
    schema = PasswordChangeSchema(context={'old_password': data.get('old_password')})
    try:
        # 使用schema验证数据
        schema.load(data)
    except Exception as e:
        return jsonify({"msg": str(e), "errors": e.messages if hasattr(e, 'messages') else None}), 400
    
    # 验证旧密码
    if not current_user.check_password(data['old_password']):
        return jsonify({"msg": "旧密码不正确"}), 401
    
    # 设置新密码
    current_user.set_password(data['new_password'])
    db.session.commit()
    
    return jsonify({"msg": "密码修改成功"}), 200 